Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

266
Views
keep getting this errror :" Cast to ObjectId failed for value" using mongodb with nodejs

I am new to coding and trying to build an APi using NOde js, express and mongodb

here is my code

router.get('/:id', async(req, res) => {  
console.log(req.params.id);
try{    
        const show = await Show.findById(req.params.id);
        const _iD = show._id.toHexString()
        console.log(_iD );
        if(req.params.id === _iD){
        res.json(show);      
        } else {
            res.send("not right ID");
        }
}

catch(err){
    console.log("error" + err)
}
})

it not working out,if "you enter a wrong ID intentionally " and should get " not right ID ", but it gets "Cast to Object ID failed for value".

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Try out this function

function isMongooseId(id) {
    var valid = false;
    try{
        if(id == mongoose.Types.ObjectId(""+id)) valid = true;
    } catch(e){
        valid = false;
    }
    return valid;
}

// You can use it like this,

if(isMongooseId(req.params.id)) {
    // Perform your db operation
}
about 4 years ago · Juan Pablo Isaza Report

0

Make sure the "intentionally wrong ID" still respect the objectId syntax (24 hexadecimal characters i would say). Otherwise you will fail at the Show.findById and jump right into the catch.

Then, i'm not sure of what your trying to do.

If you provide an ID that is not present in the collection, Show.findById will not return any object so you won't be able to get its ID with show._id.toHexString() and you will, again, jump to the catch.

And if the ID is in the collection, req.params.id === _iD will always be true and you will never reach the else.

Instead you should just check if show contain an object

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!